package je3.nio;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketTimeoutException;

/**
 * Connect to a daytime server using the UDP protocol.
 * We use java.net instead of java.nio because DatagramChannel doesn't honor
 * the setSoTimeout( ) method on the underlying DatagramSocket
 */
public class DaytimeClient {
    public static void main(String args[]) throws java.io.IOException {
        // Figure out the host and port we're going to talk to
        String host = "localhost";
        int port = 13;
        if (args.length > 1) port = Integer.parseInt(args[1]);

        // Create a socket to use
        DatagramSocket socket = new DatagramSocket();

        // Specify a 1-second timeout so that receive( ) does not block forever.
        socket.setSoTimeout(1000);

        // This buffer will hold the response.  On overflow, extra bytes are
        // discarded: there is no possibility of a buffer overflow attack here.
        byte[] buffer = new byte[512];
        DatagramPacket packet = new DatagramPacket(buffer, buffer.length,
                new InetSocketAddress(host, port));

        // Try three times before giving up
        for (int i = 0; i < 3; i++) {
            try {
                // Send an empty datagram to the specified host (and port)
                packet.setLength(0);  // make the packet empty
                socket.send(packet);  // send it out

                // Wait for a response (or time out after 1 second)
                packet.setLength(buffer.length); // make room for the response
                socket.receive(packet);          // wait for the response

                // Decode and print the response
                System.out.print(new String(buffer, 0, packet.getLength(),
                        "US-ASCII"));
                // We were successful, so break out of the retry loop
                break;
            }
            catch (SocketTimeoutException e) {
                // If the receive call timed out, print error and retry
                System.out.println("No response");
            }
        }

        // We're done with the channel now
        socket.close();
    }
}
